package jgrouse.jgdoc.elements;

import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

import jgrouse.jgdoc.api.IComment;
import jgrouse.jgdoc.api.IDocElement;
import jgrouse.jgdoc.api.IDocElementList;
import jgrouse.jgdoc.api.IDocManager;
import jgrouse.jgdoc.api.IRefContainer;

public abstract class BaseRefContainer extends DocElement implements IRefContainer
{

	private static final long serialVersionUID = -4378279670486426250L;
	protected Map<String, RefElement> m_children;
	
	public BaseRefContainer()
	{
		super();
	}
	
	public BaseRefContainer(IComment pComment)
	{
		super();
		setComment(pComment);
	}

	public IDocElementList all()
	{
		IDocElementList result = new DocElementList();
		for (RefElement ref : m_children.values())
		{
			result.add(ref.getRef());
		}
		return result;
	}

	protected void init()
	{
		super.init();
		m_children = new TreeMap<String, RefElement>();
	}


	public IDocElement getChild(String refName)
	{
		RefElement re = m_children.get(refName);
		return re == null? null : re.getRef();
	}

	public IDocElementList get(String tagName)
	{
		IDocElementList result = new DocElementList();
		for (RefElement re : m_children.values())
		{
			if (re.getRef().getCommentType().equals(tagName))
			{
				result.add(re.getRef());
			}
		}
		return result;
	}
	
	public boolean isContainer()
	{
		return true;
	}
	
	protected String getRootPath(String delimiter)
	{
		StringTokenizer st = new StringTokenizer(this.getFullName(), delimiter);
		StringBuffer buf = new StringBuffer();
		for (int i = 1; i < st.countTokens(); i++)
		{
			buf.append("../");
		}
		return buf.toString();
	}
	
	public String getRootPath()
	{
		return getRootPath(".");
	}
	
	public void cleanupPrivates(IDocManager pDocManager)
	{
		Iterator<Map.Entry<String, RefElement>> iter = m_children.entrySet().iterator();
		while (iter.hasNext())
		{
			Map.Entry<String, RefElement> item = iter.next();
			if (pDocManager.get(item.getValue().getName()) == null)
			{
				iter.remove();
			}
			
		}
		
		
	}


}
